package com.example.barry.pdf;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import android.os.Handler;
import android.os.Message;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.barry.pdf.wheel.NumericWheelAdapter;
import com.example.barry.pdf.wheel.OnWheelScrollListener;
import com.example.barry.pdf.wheel.WheelView;
import com.google.analytics.tracking.android.EasyTracker;
import com.sanm.document.pdf.DocumentView;
import com.sanm.document.pdf.OnTouchActionListener;
import com.sanm.document.pdf.PageChangeListener;
import com.sanm.document.pdf.PlayPDFStatusListener;
import com.sanm.function.file.FileHelper;
import com.sanm.function.net.http.NetDownFile;
import com.sanm.function.net.http.OnProgressUpdateListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SlaveActivity extends Activity implements View.OnClickListener{

    private final int REFRESH_THIME = (int) (2 * 60 * 60 * 1000);

    private DocumentView documentView;
    private List<DocObject> listDocs;
    HashMap<String, String> pdfHashMap = new HashMap<String, String>();
    private WheelView pageWheel;
    private boolean wheelScrolled = false;
    private Timer timer ;
    private DocObject currentPDF;
    private ImageView playButton;
    private LinearLayout operationButtonList,mLinearLayout;
    private TextView messages;

    private Context mContext;
    private LinearLayout.LayoutParams mLayoutParams;
    private Button[] buttons ;

    Handler pdfShowHandler = new Handler();
    private MyApplication myApplication;
    private Socket socket;
    private ServerSocket mServerSocket = null;
    private AcceptThread mAcceptThread ;
    private ReceiveThread mReceiveThread;
    private int numb ;
    private String[] URLPdf = null;;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    numb = URLPdf.length;
                    numb = URLPdf.length;
                    NetDownFile  netDownFile= new NetDownFile(SlaveActivity.this,showPDF,PDFEnum.getSavePdfFolder(),currentPDF.getName()+"_"+currentPDF.getVersion(),PDFEnum.TYPE_FILE_PDF);
                    currentPDF.setUrl(URLPdf[0]);
                    netDownFile.execute(currentPDF.getUrl());
                    if (numb>1) {
                        PDFNumber();
                    }
                    break;
                case 0:
                    displayToast("success");
                    break;

                case 2:
                    displayToast("master disconnect");
                   try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }

    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_pdf_activity);
        listDocs = new ArrayList<DocObject>();//) data.getSerializable("Docs");
        currentPDF = new DocObject();
        initView();
        init();
    }

    private void PDFNumber(){
        mContext = this;
        mLinearLayout = (LinearLayout)findViewById(R.id.PDFnumber);
        mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        buttons = new Button[numb];
        Log.i("NUMB",""+numb);
        for (int i = 0 ; i<numb ;i++){
            buttons[i] = new Button(mContext);
            int temp = i;
            buttons[i].setId(i);
            buttons[i].setText(String.valueOf(temp+1));
            mLinearLayout.addView(buttons[i],mLayoutParams);
            buttons[i].setOnClickListener(this);
        }
    }

    public void onClick(View view){
        for (int i = 0;i<buttons.length;i++){
            if(view.getId() == buttons[i].getId()){
                NetDownFile  netDownFile= new NetDownFile(this,showPDF,PDFEnum.getSavePdfFolder(),currentPDF.getName()+"_"+currentPDF.getVersion(),PDFEnum.TYPE_FILE_PDF);
                currentPDF.setUrl(URLPdf[i]);
                netDownFile.execute(currentPDF.getUrl());
            }
        }
    }

    private void netDownloadFile() {
        NetDownFile netDownFile = new NetDownFile(this, showPDF, PDFEnum.getSavePdfFolder(), currentPDF.getName() + "_" + currentPDF.getVersion(), PDFEnum.TYPE_FILE_PDF);
        netDownFile.execute(currentPDF.getUrl());
    }


    private void init() {
        mAcceptThread = new AcceptThread();
        mAcceptThread.start();

    }



    private class AcceptThread extends Thread{
        @Override
        public void run() {
            try {
                mServerSocket = new ServerSocket(30000);
                while (true){
                    try {
                        socket = mServerSocket.accept();
                        try {
                            sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }catch (Exception e){
                            Log.i("e",e.getMessage());
                        }
                        Message msg = mHandler.obtainMessage();
                        msg.what = 0;
                        mHandler.sendMessage(msg);//返回连接成功的信息
                        //开启mReceiveThread线程接收数据
                        mReceiveThread = new ReceiveThread(socket);
                        mReceiveThread.start();
                   }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //定义接收数据的线程
    private class ReceiveThread extends Thread{
        private InputStream is = null;
        private String read;
        //建立构造函数来获取socket对象的输入流
        public ReceiveThread(Socket sk){
            try {
                is = sk.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
          while (true){
              try {
                  sleep(500);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              BufferedReader br = null;
              try {
                  br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              }
              try {
                  //读客户端端发来的数据，阻塞直到收到结束符\n或\r
                  read = br.readLine();
                  Log.i("客户端传来",read);
                  String string = (String) read;
                  String str = string.substring(1,string.length()-1);
                  URLPdf = str.split(", ");
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (NullPointerException e) {
                  //防止服务器端关闭导致客户端读到空指针而导致程序崩溃
                  Message msg = mHandler.obtainMessage();
                  msg.what = 2;
                  mHandler.sendMessage(msg);
                  //发送信息通知用户客户端已关闭
                  break;
              }
              //用Handler把读取到的信息发到主线程
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = URLPdf;
                    mHandler.sendMessage(msg);

          }

        }

    }

    protected void onDestroy() {
        super.onDestroy();
        //清空消息队列，防止Handler强引用导致内存泄漏
        try {mHandler.removeCallbacksAndMessages(null);
            socket.close();
            mServerSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void displayToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    OnProgressUpdateListener onProgressUpdate=new OnProgressUpdateListener(){
        public void action(Integer total, Integer sum,String sProgress) {
            messages.setText("Loading....."+sProgress);
        }};
    private void initView() {

        operationButtonList=(LinearLayout) findViewById(R.id.show_pdf_layout_operation_button_list);

        TextView listNumber=(TextView) findViewById(R.id.show_pdf_view_text_pdf_number);
        listNumber.setText(listDocs.size()+"");
        messages=(TextView) findViewById(R.id.show_pdf_view_text_message);

        ImageView listButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_pdf_list);
        listButton.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v) {
                final String[] mList=new String [listDocs.size()];

                for(int i=0;i<listDocs.size();i++){
                    mList[i]=listDocs.get(i).getName();

                }
                AlertDialog.Builder listDia=new AlertDialog.Builder(SlaveActivity.this);
                listDia.setTitle("PDF List");
                listDia.setItems(mList, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        currentPDF=listDocs.get(which);
                        if(!pdfHashMap.containsKey(currentPDF.getName()+"_"+currentPDF.getVersion())){
                            netDownloadFile();
                        }else{
                            showPDF.sendMessage(new Message());
                        }
                    }
                });
                listDia.create().show();

            }});

        ImageView zoominButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_zoomin);
        zoominButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                try{
                    documentView.zoomIn();
                }catch(Exception E){}
            }});

        ImageView zoomoutButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_zoomout);
        zoomoutButton.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v) {
                try{
                    documentView.zoomOut();
                }catch(Exception E){}
            }});

        playButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_play);
        playButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                if (documentView!=null){
                    pdfShowHandler.removeCallbacks(refreshPDFView);
                    if(documentView.isStopPlay()){
                        documentView.stopPlay();
                    }else{
                        playPDF.sendMessage(new Message());
                        pdfShowHandler.postDelayed(refreshPDFView, REFRESH_THIME);
                    }
                }else{
                    playButton.setImageResource(R.drawable.button_pdf_play);
                }
            }});

        ImageView playUpButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_play_speed_up);
        playUpButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                if (documentView!=null){
                    documentView.playSpeedUp();
                }
            }});

        ImageView playDownButton=(ImageView) findViewById(R.id.show_pdf_view_image_button_play_speed_down);
        playDownButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                if (documentView!=null){
                    documentView.playSpeedDown();
                }
            }});
        initWheel(R.id.show_pdf_view_button_page_select);
    }

    private void initWheel(int id) {
        pageWheel = (WheelView) findViewById(id);
        pageWheel.setAdapter(new NumericWheelAdapter(0,0));
        pageWheel.setCurrentItem((int) (Math.random() * 10));
        pageWheel.setCyclic(false);
        pageWheel.setInterpolator(new AnticipateOvershootInterpolator());
        pageWheel.setCurrentItem(0);
        pageWheel.addScrollingListener(scrolledListener);
        pageWheel.setVisibility(View.GONE);
    }

    //
    // Wheel scrolled listener
    OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
        public void onScrollingStarted(WheelView wheel) {


        }
        public void onScrollingFinished(WheelView wheel) {
            if ( wheelScrolled ==false){
                wheelScrolled =true;
            }else if (wheelScrolled&&documentView != null) {
                wheelScrolled=false;
                Message msg = new Message();
                if (changePageHandler!=null)
                    changePageHandler.sendMessage(msg);
            }

        }
    };

    private Handler changePageHandler = new Handler(){
        public void handleMessage(Message msg) {

            if(pageWheel!=null&& documentView!=null && documentView.isShown()){
                try{
                    if ((pageWheel.getCurrentItem()!=documentView.getCurrentPage())&&documentView.getPageCount()>0){
                        documentView.goToPage(pageWheel.getCurrentItem());
                    }
                }catch(Exception e){}
            }
        }
    };


    private Handler showPDF = new Handler(){
        public void handleMessage(Message msg) {
            Bundle data=msg.getData();
            if(data!=null){
                if (data.getString(NetDownFile.KEY_DOWNLOND_ERROR)!=null){
                    if (data.getString(NetDownFile.KEY_DOWNLOND_ERROR).length()>0){
                        Message msgs=new Message();
                        Bundle b=new Bundle();
                        b.putString("data", data.getString(NetDownFile.KEY_DOWNLOND_ERROR));
                        msgs.setData(b);
                        errorHandler.sendMessage(msgs);
                        if(pdfShowLayout==null){
                            pdfShowLayout = (LinearLayout)findViewById(R.id.show_pdf_layout_pdf_view);
                        }
                        return;
                    }else{
                        pdfHashMap.put(currentPDF.getName()+"_"+currentPDF.getVersion(), data.getString(NetDownFile.KEY_FILE_URL));
                    }
                }
            }
            showPDFFunction (pdfHashMap.get(currentPDF.getName()+"_"+currentPDF.getVersion()),currentPDF.getStartPage(),currentPDF.getEndPage(),true);
        }
    };

    LinearLayout pdfShowLayout ;
    private void showPDFFunction(String fileUrl,int startPage,int endPage,boolean isStopPlay){
        try{
            //startPage=endPage=0;
            if(pdfShowLayout==null){
                pdfShowLayout = (LinearLayout)findViewById(R.id.show_pdf_layout_pdf_view);
            }
            if (documentView!=null){
                documentView.recycle();
            }
            pdfShowLayout.removeAllViews();
            documentView  = new DocumentView(this);
            pdfShowLayout.addView(documentView);

            documentView.openFile(fileUrl,PDFEnum.getSavePdfFolder());
            pageWheel.setAdapter(new NumericWheelAdapter(1, documentView.getPageCount()));
            pageWheel.addScrollingListener(scrolledListener);
            pageWheel.setCurrentItem(0);
            documentView.setOnPageChangeListener(new PageChangeListener(){
                public void PageChange(int index) {
                    if (!wheelScrolled)
                        pageWheel.setCurrentItem(index);
                }
            });
            documentView.setOnPlayStatusListener(new PlayPDFStatusListener(){
                public void onStatusChange(boolean isPlay) {
                    if (isPlay){
                        playButton.setImageResource(R.drawable.button_pdf_pause);
                    }else{
                        playButton.setImageResource(R.drawable.button_pdf_play);
                    }
                }});
            documentView.setOnTouchActionListener(onTouchActionListener);
            //documentView.showDocument(0,0,R.drawable.ico_page_lock);
            documentView.showDocument(startPage,endPage,R.drawable.ico_page_lock);

            pdfShowHandler.removeCallbacks(refreshPDFView);
            pdfShowHandler.postDelayed(refreshPDFView, REFRESH_THIME);
            messages.setText("");
            if (isStopPlay)
                playPDF.sendMessage(new Message());
        }catch(Throwable e){
            e.printStackTrace();
            //instance.sendWorkCenterMessage("PDF is incorrect!");
            Message msg=new Message();
            Bundle b=new Bundle();
            b.putString("data", "PDF is incorrect!");
            messages.setText(e.getMessage());
            msg.setData(b);
            errorHandler.sendMessage(msg);
            try{
                new FileHelper().delFile(pdfHashMap.get(currentPDF.getName()+"_"+currentPDF.getVersion()));
            }catch(Exception ex){

            }
            if (documentView!=null){
                documentView.recycle();
            }
            pageWheel.setVisibility(View.GONE);
            try{
                if(pdfShowLayout!=null)
                    pdfShowLayout.removeAllViews();
            }catch(Exception ex){
            }
            pdfHashMap.remove(currentPDF.getName()+"_"+currentPDF.getVersion());
            if (listDocs!=null&& listDocs.size()>0){
                operationButtonList.setVisibility(View.VISIBLE);
            }
        }
    }
    private Handler playPDF = new Handler(){
        public void handleMessage(Message msg) {
            if (documentView!=null);
            documentView.startPlay();
        }
    };

    Runnable refreshPDFView=new Runnable(){
        public void run() {
            Log.w("refreshPDFView", "start");
            try{
                if (documentView!=null){
                    Log.w("refreshPDFView", "work");
                    int playSpeed= documentView.getPlaySpeed();
                    final int currentPage=documentView.getCurrentPage();
                    boolean isStopPlay=documentView.isStopPlay();
                    final int x=documentView.getScrollX();
                    final int y=documentView.getScrollY();
                    final float zoom = documentView.getZoom();
                    showPDFFunction(documentView.getFileUrl(),documentView.getStartPage(),documentView.getEndPage(),false);
                    documentView.setPlaySpeed(playSpeed);
                    pdfShowHandler.postDelayed(new Runnable(){
                        public void run() {
                            documentView.setZoom(zoom);
                        }}, 500l);
                    pdfShowHandler.postDelayed(new Runnable(){
                        public void run() {
                            documentView.goToPage(currentPage);
                        }}, 900l);
                    pdfShowHandler.postDelayed(new Runnable(){
                        public void run() {
                            documentView.moveXY(x,y);
                        }}, 1300l);
                    if (isStopPlay){
                        playPDF.sendMessage(new Message());
                    }
                }
            }catch(Exception e){ Log.w("refreshPDFView", "error "+e.getMessage());}
            Log.w("refreshPDFView", "end");
        }
    };

    private Handler errorHandler = new Handler(){
        public void handleMessage(Message msg) {
            Bundle data=msg.getData();
            showPrompt(data.getString("data"));
        }
    };
    private void showPrompt(String msg){
        new AlertDialog.Builder(this)
                .setTitle(R.string.error_download_file)
                .setMessage(msg)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialoginterface, int i){
                                dialoginterface.dismiss();
                            }
                        }).show();
        messages.setText( this.getResources().getString(R.string.error_download_file)+"\n"+msg);
    }


    OnTouchActionListener onTouchActionListener=new OnTouchActionListener(){
        public void action() {
            if (operationButtonList.getVisibility()!=View.VISIBLE){
                operationButtonList.setVisibility(View.VISIBLE);
                pageWheel.setVisibility(View.VISIBLE);
            }
            if (timer!=null){
                timer.cancel();
                timer.purge();
                timer = null;
            }
            timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    handler.sendMessage(message);
                }
                Handler handler = new Handler() {
                    public void handleMessage(Message msg) {
                        operationButtonList.setVisibility(View.GONE);
                        pageWheel.setVisibility(View.GONE);
                        super.handleMessage(msg);
                    }
                };
            };
            timer.schedule(task, 15000);
        }};

}
